package www.dianbaozu.com.ui.manage

import android.os.Bundle
import android.os.Parcelable
import android.view.View
import androidx.annotation.NonNull
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.dragswipe.DragAndSwipeCallback
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.module.BaseDraggableModule
import com.chad.library.adapter.base.module.DraggableModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dylanc.loadinghelper.ViewType
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentChannelManagementBinding
import www.dianbaozu.com.extension.requestUniversally
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.extension.nav
import www.wen.com.common.lib.extension.observeObject
import www.wen.com.common.lib.extension.postObject
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA_SYSTEM_GROUPS_COUNTS
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_SERVER_ID
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import java.util.*


/**
 * @author WEN
 * @Description:频道管理-频道排序
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class ChannelManagementFragment : BaseLoadingFragment<FragmentChannelManagementBinding>(),
    View.OnClickListener,
    OnItemChildClickListener,
    OnItemClickListener {

    val mBaseApiViewModel: BaseApiViewModel by viewModels()

    private lateinit var mSortAdapter: SortAdapter

    lateinit var mTitleBarUniversalAdapter: TitleBarUniversalAdapter

    private var mGroups: ArrayList<ServerGroupIncludeEntity> = ArrayList()

    private var mIndexes: ArrayList<Int> = ArrayList()

    /**
     * true-模式编辑,false-排序模式
     */
    private var mIsEditMode: Boolean = true

    override val viewModel: BaseViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
        requireActivity(),
        tilte = getString(R.string.channel_management),
        isShowRightText = true,
        rightText = "排序",
        action = ::titleAction
    ).apply {
        mTitleBarUniversalAdapter = this
    }

    override fun getLayoutId(): Int = R.layout.fragment_channel_management

    override fun actionRight() {
        if (mIsEditMode) {
            CreateXPopupHelper.createBottomGroupPopupView(PopupViewEntity().apply {
                isShow = true
                context = requireActivity()
                resultCallBack = { view, _, _ ->
                    when (view.id) {
                        R.id.strGrouping -> {
                            nav(
                                R.id.action_channelManagementFragment_to_groupSortManagementFragment,
                                Bundle().apply {
                                    putParcelableArrayList(
                                        BUNDLE_DATA,
                                        dataConversionGroups(mSortAdapter)
                                    )
                                    putInt(
                                        BUNDLE_DATA_SYSTEM_GROUPS_COUNTS,
                                        dataConversionGroups1(mSortAdapter)
                                    )
                                    putString(
                                        BUNDLE_SERVER_ID,
                                        requireArguments().getString(BUNDLE_SERVER_ID)
                                    )
                                })
                        }
                        R.id.strFrequency -> {
                            mIsEditMode = false
                            mTitleBarUniversalAdapter.mViewHolder.tvRight.text = "完成"
                            if (mSortAdapter.isEditMode != mIsEditMode) {
                                mSortAdapter.isEditMode = mIsEditMode
                                mSortAdapter.notifyDataSetChanged()
                            }
                        }
                    }
                }
            })

        } else {
            mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                tipSuccess = "",
                isShowToastTip = false,
                request = { appDataManage -> appDataManage.requestBatch(dataConversion(mSortAdapter)) }
            ) {
                mIsEditMode = true
                mTitleBarUniversalAdapter.mViewHolder.tvRight.text = "排序"
                if (mSortAdapter.isEditMode != mIsEditMode) {
                    mSortAdapter.isEditMode = mIsEditMode
                    mSortAdapter.notifyDataSetChanged()
                }
                postObject(KeyHelper.REFRESHING_SERVER_LIST_KEY1, Object())
                toast("排序成功")
            }

        }
    }

    override fun lazyInitView() {
        observeListen()
        mLoadingHelper!!.getAdapter<TitleBarUniversalAdapter>(ViewType.TITLE).mViewHolder.tvRight
        mGroups = requireArguments().getParcelableArrayList(BUNDLE_DATA)!!
        mGroups.forEachIndexed { index, serverGroupIncludeEntity ->
            if (serverGroupIncludeEntity.type == 1) {
                val group = serverGroupIncludeEntity.content
                if (group!!.groupType == "1") {
                    mIndexes.add(index)
                }
            } else {
                val channelVO = serverGroupIncludeEntity.channelVO
                if (channelVO!!.groupType == "1") {
                    mIndexes.add(index)
                }
            }
        }
        mIndexes.add(mIndexes.size)
        dataBinding.rvChannel.layoutManager = LinearLayoutManager(requireActivity())
        dataBinding.rvChannel.adapter = SortAdapter(mIsEditMode, mGroups).apply {
            mSortAdapter = this
            draggableModule.isSwipeEnabled = false
            draggableModule.isDragEnabled = true
            draggableModule.isDragOnLongPressEnabled = false
            draggableModule.toggleViewId = R.id.imageView4
            draggableModule.itemTouchHelperCallback.setSwipeMoveFlags(ItemTouchHelper.START or ItemTouchHelper.END)
            draggableModule.itemTouchHelper =
                ItemTouchHelper(object : DragAndSwipeCallback(draggableModule) {

                    override fun getMovementFlags(
                        @NonNull recyclerView: RecyclerView,
                        @NonNull viewHolder: RecyclerView.ViewHolder
                    ): Int {

                        return if (mIndexes.contains(viewHolder.bindingAdapterPosition)) {
                            makeMovementFlags(0, 0)
                        } else {
                            super.getMovementFlags(recyclerView, viewHolder)
                        }
                    }

                    override fun onMove(
                        @NonNull recyclerView: RecyclerView,
                        @NonNull source: RecyclerView.ViewHolder,
                        @NonNull target: RecyclerView.ViewHolder
                    ): Boolean {
                        return if (mIndexes.contains(target.bindingAdapterPosition)) {
                            false
                        } else
                            super.onMove(recyclerView, source, target)
                    }

                })
            setOnItemChildClickListener(this@ChannelManagementFragment)
            setOnItemClickListener(this@ChannelManagementFragment)
        }
    }

//    mBaseApiViewModel.requestUniversally(
//    viewModelScope = lifecycleScope,
//    isShowToastTip = false,
//    request = { appDataManage ->
//        appDataManage.requestServerGroup(mServerInfo.serverId)
//    }
//    ) { groups ->
//        if (groups.isEmpty()) {
//            toast("至少需要创建一个分组")
//        } else {
//            nav(R.id.action_serverDetailsFragment_to_channelCreateFragment, Bundle().apply {
//                putParcelable(
//                    BUNDLE_DATA, BundleEntitySealed.BundleEntityFromRecommendSealed(
//                        groups[0].groupId,
//                        groups[0].groupName,
//                        mServerInfo.serverId,
//                        mServerInfo.fromType!!,
//                        mServerInfo.serverName)
//                )
//            })
//        }
//    }

    private fun observeListen() {
        //因为分组排序已经变更,需要重新变更排序
        observeObject(KeyHelper.GROUP_RESET_SORT_KEY, this, ServerGroupListEntity::class.java) {
            mSortAdapter.setList(datas)
        }
        //移除删除的分组
        observeObject(KeyHelper.GROUP_RESET_SORT_KEY1, this, Int::class.java) {
            if (this >= 0 && this < mSortAdapter.data.size) {
                mSortAdapter.removeAt(this)
            }
        }
        //更新名字改变的分组
        observeObject(KeyHelper.GROUP_RESET_SORT_KEY2, this, GroupSettingEntity::class.java) {
            mSortAdapter.data[position].content!!.groupName = groupName
            mSortAdapter.notifyItemChanged(position)
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val data = mSortAdapter.data[position]
        val isCanDelete = (position + 1) >= mSortAdapter.data.size || mSortAdapter.data[position + 1].type == 1
        val groupName = data.content!!.groupName
        val groupId = data.content!!.groupId.toString()
        nav(R.id.action_channelManagementFragment_to_groupSettingFragment, Bundle().apply {
            putParcelable(
                BUNDLE_DATA,
                GroupSettingEntity(isCanDelete, groupName, groupId, position)
            )
        })
    }

    /**
     * 跳转到频道更新页面
     */
    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val itemData = mSortAdapter.data[position]
        if (itemData.type == 2 && itemData.channelVO!!.channelType == "0") {
            val bundleEntityEditChannelSealed = matchingGroupName(position)
            if(bundleEntityEditChannelSealed.groupId == -1){
                toast("数据异常,请重新进入该页面")
                actionLeft()
            }else{
                nav(R.id.action_channelManagementFragment_to_editChannelFragment,Bundle().apply {
                    putParcelable(BUNDLE_DATA,bundleEntityEditChannelSealed)
                })
            }
        }
    }


    /**
     * 因为频道是可以拖拽排序的，所以需要找到当前频道所在的组，并设置组名和组id,还需要设置频道id等
     * @param position 频道所在的position
     */
    private fun matchingGroupName(position: Int): BundleEntitySealed.BundleEntityEditChannelSealed {
        val itemData = mSortAdapter.data[position].channelVO
        val channelId = itemData!!.channelId
        val channelName = itemData.channelName
        val channelDesc = itemData.channelDesc
        val serverId = requireArguments().getString(BUNDLE_SERVER_ID)!!
        var groupId: Int = -1
        var groupName = ""
        for (index in position downTo 0) {
            val itemDataCopy = mSortAdapter.data[index]
            if(itemDataCopy.type == 1){
                groupName = itemDataCopy.content!!.groupName
                groupId = itemDataCopy.content!!.groupId
                break
            }
        }
        return BundleEntitySealed.BundleEntityEditChannelSealed(
            groupId = groupId,
            groupName = groupName,
            serverId = serverId,
            channelDesc = channelDesc,
            channelId = channelId,
            channelName = channelName,
            position = position
        )
    }

    private fun dataConversion(adapter: BaseQuickAdapter<*, *>): List<RequestBodyParameter> {
        val requestBodyParameter = mutableListOf<RequestBodyParameter>()
        var groupId = -1
        var channelSort = -1
        adapter.data.forEach {
            val itemData = it as ServerGroupIncludeEntity
            if (itemData.type == 1) {
                groupId = itemData.content!!.groupId
                channelSort = 0
            }
            if (itemData.type != 1) {
                val channelVO = itemData.channelVO
                requestBodyParameter.add(
                    RequestBodyParameter(
                        channelId = channelVO!!.channelId.toString(),
                        groupId = groupId,
                        channelSort = channelSort
                    )
                )
                channelSort++
            }
        }
        return requestBodyParameter
    }


    private fun dataConversionGroups(adapter: BaseQuickAdapter<*, *>): ArrayList<out Parcelable>? {
        val groups = ArrayList<ServerGroupIncludeEntity>()
        adapter.data.forEach {
            val itemData = it as ServerGroupIncludeEntity
            if (itemData.type == 1 && itemData.content!!.groupType != "1") {
                groups.add(it)
            }
        }
        return groups
    }

    private fun dataConversionGroups1(adapter: BaseQuickAdapter<*, *>): Int {
        var count = 0
        adapter.data.forEach {
            val itemData = it as ServerGroupIncludeEntity
            if (itemData.type == 1 && itemData.content!!.groupType == "1") {
                count++
            }
        }
        return count
    }


    private class SortAdapter(
        var isEditMode: Boolean = true,
        groups: ArrayList<ServerGroupIncludeEntity>
    ) : BaseQuickAdapter<ServerGroupIncludeEntity, BaseViewHolder>(
        R.layout.item_grouping_sort_title,
        groups
    ), DraggableModule {

        init {
            addChildClickViewIds(R.id.tvEditGroup)
        }

        override fun convert(holder: BaseViewHolder, item: ServerGroupIncludeEntity) {
            if (item.type == 1) {
                val group = item.content
                holder.setVisible(R.id.group, true)
                holder.setVisible(R.id.channel, false)
                holder.setText(R.id.tvGroupName, group!!.groupName)
                holder.setVisible(R.id.tvEditGroup, group.groupType != "1" && isEditMode)
            } else {
                val channelVO = item.channelVO
                holder.setVisible(R.id.group, false)
                holder.setText(R.id.tvChannelName, "# ${channelVO!!.channelName}")
                holder.setVisible(R.id.channel, true)
                holder.setVisible(R.id.imageView4, channelVO.groupType != "1" && !isEditMode)
            }
        }

        override fun addDraggableModule(baseQuickAdapter: BaseQuickAdapter<*, *>): BaseDraggableModule {
            return BaseDraggableModule(baseQuickAdapter)
        }

    }


}



